package com.curso.lab1.dao.impl;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.hibernate.Query;
import org.hibernate.Session;

import com.curso.lab1.dao.intf.RoleDAO;
import com.curso.lab1.model.Role;
import com.curso.lab1.model.User;

public class RoleDAOImpl implements RoleDAO {

	private Session session;
	
	public RoleDAOImpl(Session session) {
		this.session = session;
	}
	
	@SuppressWarnings("unchecked")
	public List<Role> getAll() {
		Query query = session.createQuery("from Role");
		return query.list();
	}

	@SuppressWarnings("unchecked")
	public List<Role> getAllActive() {
		Query query = session.createQuery("from Role where isActive = true");
		return query.list();
	}

	public Role get(Long id) {
		return (Role)session.get(Role.class, id);
	}

	public boolean exists(Long id) {
		Role role = (Role)session.load(Role.class, id);
		return role != null;
	}

	public Role save(Role role) {
		session.save(role);
		return role;
	}

	public Role saveOrUpdate(Role role) {
		session.saveOrUpdate(role);
		return role;
	}

	
	public void delete(Long id) {
		Query query = session.createQuery("delete from Role where id = :id");
		query.setParameter("id", id);
		query.executeUpdate();
//		
//		Role role = get(id);
//		session.delete(role);
	}

	public void delete(Role role) {
		session.delete(role);
	}

	public List<Role> findByNamedQuery(String queryName, Map<String, Object> queryParams) {
		Query query = session.getNamedQuery(queryName);
		if (queryParams != null) {
			for (Entry<String, Object> element : queryParams.entrySet()) {
				query.setParameter(element.getKey(), element.getValue());
			}
		}
        return query.list();
	}

	public Role getRoleByName(String rolename) {
		Query query = session.createQuery("from Role where name = :name");
		query.setParameter("name", rolename);
		Role role = null;
		if (query.list().iterator().hasNext()) {
			role = (Role)query.list().iterator().next();
		}
		return role;
	}

	public void deactivateRole(Role role) {
		role.setActive(false);
		session.update(role);
	}

	@SuppressWarnings("unchecked")
	public List<Role> getAllActive(User user) {
		Query query = session.createQuery("select u.roles from User u where u.id = :user_id");
		query.setParameter("user_id", user.getId());
		return (List<Role>)query.list();
	}

}
